//
//  HandleData.m
//  UI_Project_A
//
//  Created by dllo on 16/1/25.
//  Copyright © 2016年 GH. All rights reserved.
//

#import "HandleData.h"
#import <MJExtension.h>
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"


#define FILE(STR) [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"Cache/%@.da", STR]]

@implementation HandleData


+(void)handleBlockWithurl:(NSString *)url HTTPBody:(NSString *)HTTPBody addValue:(NSString *)value HTTPHeaderField:(NSString *)HTTPHeaderField Block:(void(^)(id result)) block{
    
    
#pragma mark - 判断网络状态
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        
    
    
    NSURL * urlString = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlString];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [HTTPBody dataUsingEncoding:NSUTF8StringEncoding];
    [request addValue:value forHTTPHeaderField:HTTPHeaderField];
    
    // session对象(通道)
    NSURLSession *sesson = [NSURLSession sharedSession];
    
    
    
    
    
    // 添加任务
    NSURLSessionDataTask *task = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            
        
            NSString *cook = @"cookie/";
            NSString *behind = @".data";
            NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            
            NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [HandleData md5HexDigest:url],behind]];
            
            [data writeToFile:path  atomically:YES];
            // NSLog(@"%@", path);
            // 数据解析
            
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSError *errorJson = nil;
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJson];
            
            block(result);
            
        });
        
        }
    }];
    
    
    // 开始任务
    
    
    [task resume];

    }else {
    
        NSLog(@"没有网络(断网)");
        NSString *cook = @"cookie/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [HandleData md5HexDigest:url],behind]];
        NSLog(@"%@",libPath);
        
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        
        block(result);

    
    }
}




+ (void)handleFloewNewWithString:(NSString *)urlString Block:(void (^)(id result))block {

    
    
#pragma mark - 判断网络状态
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        
    
    
    NSString *str = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *url = [NSURL URLWithString:str];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            
        
        
        
        
        NSString *cook = @"cookie/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [HandleData md5HexDigest:urlString],behind]];
        
        [data writeToFile:path  atomically:YES];
        // NSLog(@"%@", path);
        // 数据解析
        

        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *errorJosn = nil;
            
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJosn];
            
            block(result);
        
        });
        }
    }];
    
    [task resume];

    }else {
    
        NSLog(@"没有网络(断网)");
        NSString *cook = @"cookie/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [HandleData md5HexDigest:urlString],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        
        block(result);
    
    
    
    }

}

+(void)handleForSearchUrlString:(NSString *)urlString Block:(void (^)(id))block{
    
    
    
    
    
#pragma mark - 判断网络状态
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }

    
    
    
    if (isExistenceNetwork) {
    
    NSString *str = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:str];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data) {
            
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *cook = @"cookie/";
            NSString *behind = @".data";
            NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            
            NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [HandleData md5HexDigest:urlString],behind]];
            
            [data writeToFile:path  atomically:YES];
            // NSLog(@"%@", path);
            // 数据解析
            
            
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            
            NSString *str1 = [str substringFromIndex:17];
            NSInteger length = str1.length - 2;
            NSString *str2 = [str1 substringToIndex:length];
            
            //加工字符串，转化成字典
            NSArray *array = [str2 componentsSeparatedByString:@":"];
            NSString *str3 = array.lastObject;
            NSString *string1 = [str3 substringFromIndex:1];
            string1 = [string1 substringToIndex:string1.length - 2];
            NSMutableArray *arrayUrl = [NSMutableArray array];
            if (string1.length) {
            NSArray *tempArray = [string1 componentsSeparatedByString:@","];
            for (NSString *subStr in tempArray) {
               NSString *sub1 = [subStr substringFromIndex:1];
                NSString *sub2 = [sub1 substringToIndex:sub1.length - 1];
                [arrayUrl addObject:sub2];
            }
            }
                block(arrayUrl);
        });
        }
    }];
    
    [task resume];
    
    }else{
        NSLog(@"没有网络(断网)");
        NSString *cook = @"cookie/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [HandleData md5HexDigest:urlString],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
    
        
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSString *str1 = [str substringFromIndex:17];
        NSInteger length = str1.length - 2;
        NSString *str2 = [str1 substringToIndex:length];
        
        //加工字符串，转化成字典
        NSArray *array = [str2 componentsSeparatedByString:@":"];
        NSString *str3 = array.lastObject;
        NSString *string1 = [str3 substringFromIndex:1];
        string1 = [string1 substringToIndex:string1.length - 2];
        NSMutableArray *arrayUrl = [NSMutableArray array];
        if (string1.length) {
            NSArray *tempArray = [string1 componentsSeparatedByString:@","];
            for (NSString *subStr in tempArray) {
                NSString *sub1 = [subStr substringFromIndex:1];
                NSString *sub2 = [sub1 substringToIndex:sub1.length - 1];
                [arrayUrl addObject:sub2];
            }
        }
        block(arrayUrl);

        
        
    
    }


}







/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}


+ (void)handleBlock:(void (^)(id))block{}
+ (void)handleInternet:(void (^)(id))block{}


+ (NSString *)JSONString:(NSString *)aString {
    NSMutableString *s = [NSMutableString stringWithString:aString];
    [s replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"/" withString:@"\\/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\b" withString:@"\\b" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\f" withString:@"\\f" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];


    return [NSString stringWithString:s];
}



@end
